package com.itheima.common.controller;
import com.itheima.common.entity.ResultCode;
import com.itheima.common.exception.IhrmException;
import com.itheima.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author IntelliJ IDEA
 * @date 2020/10/22  9:36
 */
public class BaseController {

    protected static final String JWTSTR="Bearer ";
    /**
     * 用户id
     */
    protected String userId;
    /**
     * 企业id
     */
    protected String companyId;

    /**
     * 企业名称
     */
    protected String companyName;

    protected Claims claims;

    protected HttpServletRequest request;

    protected HttpServletResponse response;

    /**
     * JWT方式获取用户的companyId和companyName
     */
    @ModelAttribute
    public void getCompanyNameAndCompanyId(HttpServletRequest request, HttpServletResponse vo){
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(authorization) && authorization.startsWith(JWTSTR)){
            String token = authorization.replace(JWTSTR, "");
            Claims claims = JwtUtils.parseJwt(token);
            if(claims!=null){
                this.claims=claims;
                this.companyId= (String) claims.get("companyId");
                this.companyName= (String) this.claims.get("companyName");
            }else {
                throw new IhrmException(ResultCode.UNAUTHENTICATED);
            }
        }
    }


    /**
     * shiro方式获取用户的companyId和companyName
     */
//    @ModelAttribute
//    public void getCompanyNameAndCompanyId(HttpServletRequest request, HttpServletResponse response){
//        this.request=request;
//        this.response=response;
//        //获取安全数据
//         String userInfo = (String) SecurityUtils.getSubject().getPrincipal();
//         if(StringUtils.isNotBlank(userInfo)){
//             //userInfo转为UserInfo对象
//             Gson gson=new Gson();
//             UserInfo info = gson.fromJson(userInfo, UserInfo.class);
//             this.companyId=info.getCompanyId();
//             this.companyName=info.getCompanyName();
//             this.userId=info.getUserId();
//         }
//    }
}
